C++에서는 데이터 스트림이 단순한 파이프만이 아니라, 상태를 가진 실체입니다. istream 객체를 불린 조건으로 평가하면 std::cin 프로그램은 사용자 입력이나 외부 파일의 예측할 수 없는 흐름에 적응할 수 있습니다.
1. 스트림을 진리값으로 간주하기
우리가 if (std::cin >> val)와 같은 표현을 사용할 때, 식은 true 스트림이 유효한 경우에만 반환됩니다. 만약 스트림이 끝파일(EOF) 또는 잘못된 데이터 타입을 만날 경우, "실패" 상태로 전환되어 false를 반환합니다.
2. 고정점과 탐지기
데이터 변화를 추적하기 위해 우리는 currVal (상태 고정점)과 val (활동적인 탐지기)를 정의합니다. 논리는 들어오는 탐지기를 고정점과 비교하는 데 의존합니다. 불일치가 발생하면 "상태 변경" 보고서가 트리거되며, 이는 최소한의 메모리로 무한한 데이터를 처리할 수 있게 해줍니다.
3. 다중 읽기 작업
C++는 스트림 읽기 연쇄를 허용합니다: cin >> i >> j;이 문장은 첫 번째 값을 i 에, 두 번째 값을 j에 저장하며, 복잡한 레코드를 효율적으로 읽는 방법을 제공합니다.
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
Exercise 1.17: What happens in the counting program if all input values are equal?
The program crashes due to an infinite loop.
The program prints the count for every single input entered.
The program accumulates the count and prints a single result only after EOF is reached.
The program skips all inputs because no state change is detected.
✅ Correct!
Correct. Since the `val == currVal` condition is always true, the `else` block never triggers until the `while` loop finishes.❌ Incorrect
The `else` block only executes when a *new* value is found; if all are the same, we only see the final summary after the stream ends.QUESTION 2
What does the expression
std::cin >> val return when used in a while loop condition?The integer value that was just read.
A reference to the istream object, which is then evaluated as a boolean.
The number of characters remaining in the buffer.
A pointer to the memory address of val.
✅ Correct!
Exactly! The stream object itself is returned, and C++ checks its state (valid/invalid) to decide if the loop continues.❌ Incorrect
It returns the stream. If the stream encountered an error or EOF, the boolean evaluation becomes false.QUESTION 3
Exercise 1.20: If you use
while (std::cin >> trans) with a Sales_item object, how does the loop detect the end of input?It waits for a specific 'END' string in the transaction data.
The Sales_item class has a built-in timer.
The istream operator for Sales_item is overloaded to return the stream state, allowing EOF detection.
It only stops when it reads a transaction with a price of zero.
✅ Correct!
Correct. Class objects can define how they interact with streams so they behave just like built-in types (int, double).❌ Incorrect
The behavior is consistent with basic types: the stream state determines the loop termination.QUESTION 4
In the syntax
std::cin >> i >> j;, what determines which variable gets the first piece of data?The alphabetical order of variable names.
The variable type (int vs float).
The sequence from left to right.
The compiler's optimization settings.
✅ Correct!
The stream extracts data sequentially. The first value in the buffer goes into the first variable on the left.❌ Incorrect
Streams are processed from left to right, matching the input order.QUESTION 5
What happens if a user types 'ABC' when the program expects
std::cin >> val (where val is an int)?The program converts the characters to their ASCII integer sums.
The stream enters a 'fail' state and the condition
(std::cin >> val) becomes false.The program prompts the user to re-enter the data automatically.
The integer 0 is stored in val and the program continues.
✅ Correct!
Type mismatch causes the stream state to fail, which is why our `while` loops stop gracefully on bad input.❌ Incorrect
Incorrect input doesn't just return 0; it breaks the stream's validity.Mastering Stream Transitions
Analysis of data tracking and class streams
You are developing a transaction logger for a bookstore. You need to read multiple transactions using the Sales_item class. If the input is 'ISBN-001 5 20.0 ISBN-001 2 20.0 ISBN-002 1 15.0', your logic must detect the ISBN change.
Q
1. Provide the model code for reading a set of book sales transactions and writing them to standard output (Exercise 1.20).
Solution:
Solution: cpp #include <iostream> #include "Sales_item.h" int main() { Sales_item trans; while (std::cin >> trans) { std::cout << trans << std::endl; } return 0; }
Solution: cpp #include <iostream> #include "Sales_item.h" int main() { Sales_item trans; while (std::cin >> trans) { std::cout << trans << std::endl; } return 0; }
Q
2. Explain why the program in Exercise 1.20 works for both a single transaction and a thousand transactions without modifying the code.
Solution:
The program uses an **iterative stream processing** model. The `while (std::cin >> trans)` loop continually probes the stream. As long as a valid transaction is available, the loop body executes. It only terminates when the system signals an EOF (End-of-File) or data failure, making it agnostic to the input size.
The program uses an **iterative stream processing** model. The `while (std::cin >> trans)` loop continually probes the stream. As long as a valid transaction is available, the loop body executes. It only terminates when the system signals an EOF (End-of-File) or data failure, making it agnostic to the input size.
Q
3. In a counting logic scenario, what happens if the input has no duplicated values? (Exercise 1.17)
Solution:
If no values are duplicated, the `else` block will execute for every single input after the first `currVal` is set. Each time a new `val` is read, it will not match `currVal`, causing the program to print that the previous value occurred exactly 1 time before resetting the anchor.
If no values are duplicated, the `else` block will execute for every single input after the first `currVal` is set. Each time a new `val` is read, it will not match `currVal`, causing the program to print that the previous value occurred exactly 1 time before resetting the anchor.